package com.hsmpay.mobile.ds.impl;

import com.hsmpay.common.pojo.BasePojo;
import com.hsmpay.common.pojo.qian4.Qian4SendLog;
import com.hsmpay.common.util.NumberUtil;
import com.hsmpay.mobile.dao.other.SettingsDao;
import com.hsmpay.mobile.dao.terminal.TchannelDao;
import com.hsmpay.mobile.dao.terminal.TchannelMDao;
import com.hsmpay.mobile.dao.trans.TransOrderDao;
import com.hsmpay.mobile.ds.DS_UinpayPayService;
import com.hsmpay.mobile.pojo.other.Settings;
import com.hsmpay.mobile.pojo.terminal.Tchannel;
import com.hsmpay.mobile.pojo.terminal.TchannelM;
import com.hsmpay.mobile.pojo.trans.TransOrder;
import com.hsmpay.qian4.pojo.BalanceResult;
import com.hsmpay.qian4.pojo.PurchaseResult;
import com.hsmpay.qian4.pojo.RevocationResult;
import com.hsmpay.qian4.pojo.send.SendParam;
import com.hsmpay.yl8583.service.UinpayPayService;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by zhy on 15/9/12.
 */
@Service("ds_UinpayPayService")
public class DS_UinpayPayServiceImpl implements DS_UinpayPayService<BasePojo,Long> {
    @Resource(name="tchannelDao")
    TchannelDao<Tchannel,Long> tchannelDao;
    @Resource(name="transOrderDao")
    private TransOrderDao<TransOrder,String> transOrderDao;//交易订单
    @Resource(name="tchannelMDao")
    private TchannelMDao<TchannelM,String> tchannelMDao;//通道商户号表
    @Resource(name="settingsDao")
    private SettingsDao<Settings,Long> settingsDao;//配置表

    private Long flRoleId = 2l;
    private Long fdRoleId = 3l;
    private static int tchannelId = 43;

    /**
     * 获取翰鑫的配置信息
     * @return
     * @throws Exception
     */
    public Map<String, String> getUinpayConfig() throws Exception{
        Settings settings = new Settings();
        settings.setFunctionKey("CHANNEL_UIN_CONFIG");
        settings = settingsDao.searchEntity(settings);
        String mainValue = settings == null?null:settings.getMainValue();//机构号@ip:port
        /**
         * 解析mainValue
         */
        String ip = "";
        String port = "";
        if (StringUtils.isNotBlank(mainValue)){
            String[] res = mainValue.split(":");
            ip = res[0];
            port = res[1];
        }

        Map<String, String> map = new HashMap<String, String>();
        map.put("ip", ip);
        map.put("port", port);
        return map;
    }
    /**
     * 获取秘钥
     * @param tcm
     * @param str
     * @param transAmt
     * @param c_fdMoney
     * @return
     * @throws Exception
     */
    public Map<String, String> getMiYao(TchannelM tcm, String str, String transAmt, Double c_fdMoney) throws Exception {
        Map<String,String> miYao = null;
        if(StringUtils.isEmpty(str)){
            miYao = reflushMiYao(tcm,transAmt,c_fdMoney);
        }else{
            miYao = new HashMap<String, String>();
            //if(StringUtils.isEmpty(str)) return reflushMiYao(transAmt,c_fdMoney);
            String[] strA = str.split("_");
            if("-1".equals(strA[0]) || StringUtils.isEmpty(strA[2].trim())) return reflushMiYao(tcm,transAmt,c_fdMoney);
            miYao.put("batchId", strA[2]);
            miYao.put("mastKey", strA[3]);
            miYao.put("pinKey", strA[4]);
            miYao.put("macKey", strA[5]);
            miYao.put("trkKey", strA[6]);
        }
        return miYao;
    }

    /**
     * 刷新秘钥
     * @param tcm
     * @param transAmt
     * @param c_fdMoney
     * @return
     * @throws Exception
     */
    public Map<String, String> reflushMiYao(TchannelM tcm, String transAmt, Double c_fdMoney) throws Exception {
        Map<String, String> config = getUinpayConfig();
        UinpayPayService aps = new UinpayPayService(tcm.getMcode(),tcm.getTcode(),"000001",tcm.getMainKey(),null,null,null,null, config);

        Integer bankOrderNum = searchUinPayTransId();
        String miyao = aps.login(bankOrderNum.toString());
        //保存密钥
        tchannelMDao.updateMobileTcOtherById(tcm.getId(), miyao);
        return getMiYao(tcm,miyao,transAmt,c_fdMoney);
    }

    /**
     * 查询余额
     * @param send
     * @return
     * @throws Exception
     */
    public BalanceResult balanceEnquiry(Qian4SendLog send) throws Exception {
        TchannelM tcm = tchannelMDao.searchTchannelMByCode(send.getCollectionType(), send.getMerchantId(),send.getTerminalId());
        Map<String,String> miyao = getMiYao(tcm,tcm.getOtherParam(),null,null);
        Map<String, String> config = getUinpayConfig();
        UinpayPayService  aps = new UinpayPayService(send.getMerchantId(),send.getTerminalId(),miyao.get("batchId"),tcm.getMainKey(),miyao.get("mastKey"),miyao.get("pinKey"),miyao.get("macKey"),miyao.get("trkKey"), config);//getAnxinybPayService(send.getTransAmt());
        SendParam sendParam = new SendParam();
        BeanUtils.copyProperties(sendParam,send);
        return aps.balanceEnquiry(sendParam);
    }

    /**
     * 消费
     * @param send
     * @param tc
     * @return
     * @throws Exception
     */
    public PurchaseResult billPayment(Qian4SendLog send, Tchannel tc) throws Exception {
        Double c_fdMoney = NumberUtil.roundF2((tc.getFdMaxFee()/tc.getFeeRate()));

        TchannelM tcm = tchannelMDao.searchTchannelMByCode(send.getCollectionType(), send.getMerchantId(),send.getTerminalId());
        Map<String,String> miyao = getMiYao(tcm,tcm.getOtherParam(),send.getTransAmt(),c_fdMoney);
        Map<String, String> config = getUinpayConfig();
        UinpayPayService aps = new UinpayPayService(send.getMerchantId(),send.getTerminalId(),miyao.get("batchId"),tcm.getMainKey(),miyao.get("mastKey"),miyao.get("pinKey"),miyao.get("macKey"),miyao.get("trkKey"),config);

        SendParam sendParam = new SendParam();
        BeanUtils.copyProperties(sendParam,send);
        PurchaseResult rs = aps.billPayment(sendParam);
        if("00A0".equals(rs.getReqCode())){
            miyao = reflushMiYao(tcm, send.getTransAmt(), c_fdMoney);
//			rs = aps.billPayment(sendParam);
        }

        //判断商户号是否  收满  ######
//		if(){
//			qihuanJieKou(send.getTransAmt());
//		}

        Integer status = null;
        Double addUseTotal = NumberUtil.roundF2(Integer.parseInt(send.getTransAmt())/100.00);
        Double useTotal = NumberUtil.roundF2((tcm.getUseTotal()+addUseTotal));
        if(null != tcm.getTotalLimit() && tcm.getTotalLimit() < useTotal){
            status = 3;
        }
        if(!("0000".equals(rs.getReqCode()))) addUseTotal = null;
        tchannelMDao.updateTchannelMUseMoney(tcm.getId(), addUseTotal, status);//交易失败也要修改时间
        return rs;
    }
    /**
     * 冲正
     * @param send
     * @return
     * @throws Exception
     */
    public RevocationResult unBillPayment(Qian4SendLog send) throws Exception {
        Tchannel tc = tchannelDao.searchMobileTchannelByCode(send.getCollectionType());
        Double c_fdMoney = NumberUtil.roundF2((tc.getFdMaxFee()/tc.getFeeRate()));

        TchannelM tcm = tchannelMDao.searchTchannelMByCode(send.getCollectionType(), send.getMerchantId(),send.getTerminalId());

        Map<String,String> miyao = getMiYao(tcm,tcm.getOtherParam(),send.getTransAmt(),c_fdMoney);
        Map<String, String> config = getUinpayConfig();
        //冲正  重新创建接口对象
        UinpayPayService aps = new UinpayPayService(send.getMerchantId(),send.getTerminalId(),miyao.get("batchId"),tcm.getMainKey(),miyao.get("mastKey"),miyao.get("pinKey"),miyao.get("macKey"),miyao.get("trkKey"),config);

        SendParam sendParam = new SendParam();
        BeanUtils.copyProperties(sendParam,send);
        RevocationResult rr = aps.unBillPayment(sendParam);
//		if("00A0".equals(rr.getReqCode())){
//			miyao = reflushMiYao(send.getTransAmt(),c_fdMoney);
//			rr = aps.unBillPayment(send);
//		}
        return rr;
    }
    public UinpayPayService getPayService(String transAmt,Double c_fdMoney)throws Exception{
        TchannelM tcm = getTchannelM(transAmt,c_fdMoney);

        Map<String,String> miyao = getMiYao(tcm,tcm.getOtherParam(),transAmt,c_fdMoney);
        //获取主密钥 和 终端号
        return new UinpayPayService(tcm.getMcode(),tcm.getTcode(),miyao.get("batchId"),tcm.getMainKey(),miyao.get("mastKey"),miyao.get("pinKey"),miyao.get("macKey"),miyao.get("trkKey"),null);
    }

    private TchannelM getTchannelM(String transAmt,Double c_fdMoney)throws Exception{
        TchannelM tcm = null;
        Double money = 0.00;
        if(StringUtils.isNotEmpty(transAmt)){
            money = Integer.parseInt(transAmt)/100.0;
        }
        Long roleId = flRoleId ;
        if(money > c_fdMoney)roleId = fdRoleId;
        List<TchannelM> list = tchannelMDao.searchMobileTCListByCodeOrderByUseTime(tchannelId, roleId);
//		tcm = list.get(cnt%list.size());
//		cnt++;
        tcm = list.get(0);//获取第一个
        //更新使用时间
        tchannelMDao.updateTchannelMUseTime(tcm.getId());
        return tcm;
    }
    /**
     * 初始化 请求参数
     * @param
     * @param send
     * @param tc
     * @return
     * @throws Exception
     */
    public Qian4SendLog initSend(Qian4SendLog send,Tchannel tc)throws Exception{
        Double c_fdMoney = NumberUtil.roundF2((tc.getFdMaxFee()/tc.getFeeRate()));
        UinpayPayService aps = getPayService(send.getTransAmt(),c_fdMoney);

        send.setBankOrderNum(searchUinPayTransId().toString());//查询序列 获取动态流水号
        send.setBatchId(aps.batch);//批次号
        send.setMerchantId(aps.merchantId);
        send.setTerminalId(aps.terminalId);
        return send;
    }
    /**
     * 优银支付序列号
     * @return
     * @throws Exception
     */
    public Integer searchUinPayTransId() throws Exception {
        return transOrderDao.searchUinPayTransId();
    }
}
